/**
 * 快捷键定义
 */
var ShortcutKey = {};
ShortcutKey.Save = 34;
ShortcutKey.Tab = 13;
ShortcutKey.DetailAdd = 123;
var top = window.parent;

/**
 * 除掉两端空格
 */
String.prototype.trim = function(){return this.replace(/(^\s*)|(\s*$)/g,"");}
function $(id)
{
	var element = id;
	if(typeof(element) == 'string') { element = document.getElementById(id); }
	return element;
}
function $$(id)
{
	var element = id;
	if(typeof(element) == 'string') { element = document.getElementById(id); }
	return element;
}

var Element = {
    /**
     * 标记标签。第一个参数：选中标签的单元格；第二个参数：选中标签对应的 Table；第三个及以后的参数：其余的 Table。
     */
	toggle:function(){
        var td = arguments[0];
        if (td.className == 'menuChoosed'){
            return;
        }
        
        var tr = td.parentNode;
        for (var idx = 0; idx < tr.cells.length; idx++){
            if (tr.cells[idx].className == 'menuChoosed'){
                tr.cells[idx].className = 'menuNormal';
                break;


            }
        }
        
        td.className = 'menuChoosed';
        arguments[1].style.display = '';
        
		for(var idx = 2; idx < arguments.length; idx++){
		    arguments[idx].style.display = 'none';
		}
	},
	
	hide:function(){
		for(var i=0; i < arguments.length; i++){
			$$(arguments[i]).style.display = 'none';
		}
	},
	
	show:function(){
		for(var i=0; i < arguments.length; i++){
			$$(arguments[i]).style.display = '';
		}
	},
	
	remove:function(element){
		element = $$(element);
		element.parentNode.removeChild(element);
	},
	
	getHeight: function(element) {
        return $$(element).offsetHeight;
    },

    getWidth: function(element) {
        return $$(element).offsetWidth;
    }
};

function showMessage(msg)
{
    window.alert(msg);
}

function handleError(e)
{
    window.alert(e.message);
}

function loadButtons(buttons, times)
{
    //if (window.parent && window.parent.name == "main") return; yuling removed for edit BOM.2008-01-10 
    try
    {
        top.frames["toolbar"].window.loadButtons(buttons);
    }
    catch (ex)
    {
        if (typeof(times) == "undefined") { times = 1; }
        
        if (times <= 5)
        {
            window.setTimeout(function(){loadButtons(buttons, ++times);}, 200);
        }
    }
}

function openWindow(url, isShowToolbar, width, height, left, top)
{
    if(url.indexOf("?") > 0)
    {
        url += "&rnd=" + Math.random();
    }
    else
    {
        url += "?rnd=" + Math.random();
    }
    
    var left = left ? left : ((window.screen.availWidth - width) / 2);
    var top = top ? top : ((window.screen.availHeight - height) / 2);
    var features = "fullscreen=0,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=" + 
        width + ",height=" + height + ",top=" + top + ",left=" + left;
        
    if (isShowToolbar == true)
    {
        url = appPath + "/Framework/PopupFramework.aspx?url=" + url;
    }
    
    return window.open(url, "_blank", features, true);
}

function openChooseWindow(pageId, isMultiple, searchCondition, callBackFunc, width, height, left, top)
{
    if (searchCondition == undefined)
    {
        searchCondition = "";
    }
    if (callBackFunc == undefined)
    {
        callBackFunc = "";
    }

    var w = width ? width : 700;
    var h = height ? height : 450;
    var l = left ? left : ((window.screen.availWidth - w) / 2);
    var t = top ? top : ((window.screen.availHeight - h) / 2);
    var url = appPath + "/Framework/ChoosePage.aspx?CallBackFunc=" + callBackFunc + "&PageId=" + pageId + "&Multiple=" + (isMultiple ? "true" : "false") + (searchCondition ? "&SearchCondition=" + escape(searchCondition) + "&PageCondition=" + escape(searchCondition) : "") + "&rnd=" + Math.random();
    var features = "fullscreen=0,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=" + 
        w + ",height=" + h + ",top=" + t + ",left=" + l;

    return window.open(url, "_blank", features, true);
}

function openModalDialog(url, args, isShowToolbar, width, height, left, top)
{
    if(url.indexOf("?") > 0)
    {
        url += "&rnd=" + Math.random();
    }
    else
    {
        url += "?rnd=" + Math.random();
    }
    
    var features = "status:0;resizable:0;dialogWidth:" + width + "px;dialogHeight:" + height + "px;help:0;edge:sunken;";
    
    if (left && top)
    {
        features += "dialogLeft:" + left + "px;dialogTop:" + top + "px;";
    }
    
    if (isShowToolbar == true)
    {
        url = appPath + "/Framework/PopupFramework.aspx?url=" + url;
    }
   
    return window.showModalDialog(url, args, features);
}

function openModelessDialog(url, args, isShowToolbar, width, height, left, top)
{
    if(url.indexOf("?") > 0)
    {
        url += "&rnd=" + Math.random();
    }
    else
    {
        url += "?rnd=" + Math.random();
    }
    
    var features = "status:0;resizable:0;dialogWidth:" + width + "px;dialogHeight:" + height + "px;help:0;edge:sunken;";
    if (left && top)
    {
        features += "dialogLeft:" + left + "px;dialogTop:" + top + "px;";
    }
    
    if (isShowToolbar == true)
    {
        url = appPath + "/Framework/PopupFramework.aspx?url=" + url;
    }
    
    return window.showModelessDialog(url, args, features);
}

function openRouteWindow(type, recordId, width, height, left, top)
{
    var url = appPath + "/Auditing/Route.aspx?Type=" + type + "&RecordId=" + recordId;
    var w = width ? width : 380;
    var h = height ? height : 420;
    var l = left ? left : ((window.screen.availWidth - w) / 2);
    var t = top ? top : ((window.screen.availHeight - h) / 2);
    
    openModalDialog(url, window, false, w, h, l, t);
}

function getAbsolutePosition(element, attributeName)
{
    var absolutePosition = 0;

    while (element)
    {
        absolutePosition += element[attributeName];
        element = element.offsetParent;
    }

    return absolutePosition;
}

function getPattern(pattern)
{
    switch (pattern)
    {
        case "int":
            return "^-?\\d+$";
        case "uint":
            return "^\\d+$";
        case "float":
            return "^-?\\d*\\.?\\d+$";
        case "ufloat":
            return "^\\d*\\.?\\d+$";
        case "yearMonth":
            return "^[1-9]\\d{3}((0[1-9])|(1[0-2]))$";
        case "email":
            return "^[_\\w]+[\\w\\.\\-_]*@\\w+(\\.\\w+){1,2}$";
        case "year":
            return "^[1-9]\\d{3}$";
        default:
            return pattern;
    }
}

function formatDateControlValue(objDate)
{
    var dateStr = objDate.value;
    var reg, isValid = false;
    var sep = "-";
    
    reg = /^\d{8}$/;
    if (reg.test(dateStr))
    {
        dateStr = dateStr.substr(0, 4) + "/" + dateStr.substr(4, 2) + "/" + dateStr.substr(6, 2);
        isValid = true;
    }
    else
    {
        reg = /^\d{4}-\d{1,2}-\d{1,2}$/;
        if (reg.test(dateStr))
        {
            dateStr = dateStr.replace(/-/g, "/");
            isValid = true;
        }
        else
        {
            reg = /^\d{4}\/\d{1,2}\/\d{1,2}$/;
            if (reg.test(dateStr))
            {
                sep = "/";
                isValid = true;
            }
        }
    }
    
    if (isValid)
    {
        var date = new Date();
        date.setTime(Date.parse(dateStr));
        objDate.value = date.getFullYear() + sep + (date.getMonth() + 1) + sep + date.getDate();
    }
    
    return isValid;
}

function formatTimeControlValue(objTime)
{
    var timeStr = objTime.value;
    var reg = /^\d{4}$/;    
    if (reg.test(timeStr))
    {
        timeStr = timeStr.substr(0, 2) + ":" + timeStr.substr(2, 2);
        objTime.value = timeStr;
    }
    
    reg = /^[0-3]?[0-9]:[0-5]?[0-9]$/;
    return reg.test(timeStr);
}

function validateElement(element)
{  // alert(element.value);
    var errorMsg = "";
    var isValid = true;
    //检查必填域（带有 required="true" 属性的文本框）的值是否为空。
   // alert(element.required);
    if (element.required)
    {
        if (element.value.replace(/\s+$/, "") == "")
        {  
            isValid = false;
            errorMsg = "不能为空!";
             //alert("空值一");
        }
    }
   // alert(isValid && element.pattern);
    //检查用户输入的值是否符合指定的正则表达式（由控件的 pattern 属性指定）。
    //alert(isValid+"!!");
    if (isValid && element.pattern)
    {  //alert(element.pattern+"123");
        element.value = element.value.replace(/(^\s+)|(\s+$)/g, "");
       
        if (element.value == "")
        {   //alert("空值二");
            isValid = true;
        }
        else
        {
            var pattern = element.pattern;
            if (pattern == "date")
            {
                isValid = formatDateControlValue(element);            
            }
            else if (pattern == "time")
            {
                isValid = formatTimeControlValue(element);
            }
            else
            {  
                 
                pattern = getPattern(pattern);
                var reg = new RegExp(pattern);
                isValid = reg.test(element.value);
                
            }
        }
        
        if (!isValid)
        {
            errorMsg = "格式错误!";
        }
    }
   //alert("go");
    var element1 = element;
    // 如果输入框后跟了选择按钮，提示信息将插入选择按钮之后。
    if (element.nextSibling && element.nextSibling.className != null
        && element.nextSibling.className.toLowerCase() == "buttonbox")
        element1 = element.className;
        
    if (!isValid)
    {  
        if (element.isReminded)
        {    
            element1.nextSibling.innerText = errorMsg;
             
        }
        else
        {
            element.isReminded = true;
            var strHTML = "<span class='ErrorMsg'>" + errorMsg + "</span>";
            element1.insertAdjacentHTML("afterEnd", strHTML);
        }
    }
    else
    {
        if (element.isReminded)
        {
            element1.nextSibling.innerText = "";
        }
    }

    return isValid;
}

function validateInput()
{
    var pageIsValid = true;
    var elements = document.forms[0].elements;
    var element, elementCount = elements.length;
    var isFirstInvalidObject = true;
    var isValid = false;
    
    for (var i = 0; i < elementCount; i++)
    {
        element = elements(i);
        if (element.type != "text") { continue; }
        
        isValid = validateElement(element);        
        if (!isValid)
        {
            pageIsValid = false;
            
            if (isFirstInvalidObject)
            {
                try
                {
                    element.focus();
                    element.select();
                }
                catch(ex){}
                
                isFirstInvalidObject = false;
            }
        }
    }
    
    //调用页面的验证函数（如果有的话）验证用户的输入是否正确。
    if ((pageIsValid == true) && (typeof(validate) == "function"))
    {
        try
        {
            pageIsValid = validate();
        }
        catch (ex)
        {
            pageIsValid = false;
            alert(ex.message);
        }
    }
    
    return pageIsValid;
}

//yuling added clearAllRemind() and clearOneRemind(element)
function clearAllRemind()
{
    var elements = document.forms[0].elements;
    var element, elementCount = elements.length;
    for (var i = 0; i < elementCount; i++)
    {
        element = elements(i);
        if (element.type != "text") { continue; }

        clearOneRemind(element);
    }
}

function clearOneRemind(element)
{
    if (element.isReminded)
    {
        var element1 = element;
        // 如果输入框后跟了选择按钮，提示信息将插入选择按钮之后。
        if (element.nextSibling && element.nextSibling.className != null
            && element.nextSibling.className.toLowerCase() == "buttonbox")
            element1 = element.nextSibling;

        element1.nextSibling.innerText = "";
    }
}

function focusToFirstElement(objContainer)
{
    var elements, element;
    
    if (objContainer == null)
    {
        elements = document.forms[0].elements;
    }
    else
    {
        elements = objContainer.all.tags("INPUT");
    }
    
    for (var i = 0, elementCount = elements.length; i < elementCount; i++)
    {
        element = elements(i);
        if (element.readOnly == false && element.disabled == false && element.style.display != "none" 
            && element.style.visibility != "hidden" && element.type != "hidden")
        {
            try
            {
                element.focus();
                if (element.type == "text") { element.select(); }
            }
            catch (ex) {}
            break;
        }
    }
}

function processKeyboardEvent()
{
    /*回车会跑两次onchange事件
    if (event.keyCode == 13 || event.keyCode == 9) //yuling added 2008-09-23
    {
        if ( event.srcElement.onchange != null )
        {
            event.srcElement.fireEvent("onchange");
            //if ( !isSuccess ) { isSuccess = true; return; }
        }
    }*/

    if (event.keyCode == 27) //Esc
    {
        try { cancel(); } catch (ex){}
    }
    //只处理Tab键而没处理LostFocus事件，结果不一致，需在LostFocus事件中加上validateElement(element)。yuling.
    else if (event.keyCode == ShortcutKey.Tab || event.keyCode == 9) //Tab
    {
        var element = event.srcElement;
        if (element.type == "text")
        {
            if(validateElement(element))
            {
                event.keyCode = 9;
            }
        }
        else if(element.type != "button")
        {
            event.keyCode = 9;
        }
    }
}

window.onload=function ()
{
    focusToFirstElement();
}

function closePopup() {
    var header = top.frames["header"];
    if (header) {
        //if (header._wtype == 0) return;
        if (header._timer > 0) {
            window.clearInterval(header._timer);
            header._timer = 0;
        }
        header._wtype = -1;
        if (header._popup == null /*|| !header._popup.isOpen*/) return;
        header._popup.hide();
        //header._popup = null;
    }
}

function closePopup2() {
    var statusBar = top.frames["statusBar"];
    if (statusBar) {
        statusBar.closePopup();
    }
}

document.attachEvent("onclick", closePopup2);

/**
 * 获取指定元素的具有给定 tagName 属性的父元素。 
 */
function getAncestorElementByTagName(obj, tagName)
{
    tagName = tagName.toUpperCase();
    
    while(obj && obj.tagName != tagName)
    {           
        obj = obj.parentElement;
    }
  
    return obj;
}

/**
 * 获取输入的时间值，为空时转换为最大时间值。
 */
function getTimeValue( strTime )
{
    return (strTime.trim() == "" ? "00:00" : strTime);
}

/**
 * 获取输入的日期值，为空时转换为最大日期值。
 */
function getDateValue( strDate )
{
    return (strDate.trim() == "" ? "9999-12-31" : strDate);
}

/**
 * 设置日期值，为最大日期值时转换为空。
 */
function setDateValue( strDate )
{
    return ((strDate.trim().substring(0, 10) == "9999-12-31" || strDate.trim().substring(0, 10) == "9999/12/31") ? "" : strDate);
}

function dateToShortDateString( strDate )
{
    if (strDate.indexOf("9999") != -1) return "";
    if (strDate.indexOf(" ") == -1)    return strDate;
    return strDate.substring(0, strDate.indexOf(" "))
}

function dateToChineseDateString(strDate)
{
    if(strDate.trim() == "") return "";
    
    var arrDate = strDate.split("-");
    
    return arrDate[0] + "年" + arrDate[1] + "月" + arrDate[2] + "日";
}

/**
 * 获取输入的数字值，为空时转换为默认数字值。
 */
function getNumeralValue( strNumeral, defaultNumberal )
{
    return (strNumeral.trim() == "" ? defaultNumberal : strNumeral);
}

/**
 * 设置状态栏信息。
 * position 为 "top" 时，信息显示在 toolbar 内。
 */
function setStatusMessage(message, position)
{
    if(position && (position.toLowerCase() == "top") )
    {
        if ( typeof(top.frames["toolbar"]) == "object" )
            top.frames["toolbar"].window.setStatusMessage(message); 
    }
    else
    {
        if ( typeof(top.frames["statusBar"]) == "object" )
            top.frames["statusBar"].window.setStatusMessage(message);
    }
}

/**
 * 返回具有相同名字元素的值组成的字符串 
 * separator    : 分隔符，默认为","
 * defaultValue : 当输入为空时的替换值，默认为""
 */
function getValueByElementName(elementName, separator, defaultValue)
{    
    separator = separator ? separator : ",";
    defaultValue = defaultValue ? defaultValue : "";
    var objArray = document.getElementsByName(elementName);
    var valueArray = new Array();
    var theValue;
    for(var i=0; i<objArray.length; i++)
    {
        theValue = (objArray[i].value == "" ? defaultValue : objArray[i].value);
        valueArray.push(theValue);
    }
    return (valueArray.join(separator));
}

/*
*返回四舍五入后的值
*objValue :要四舍五入的值
*index :保留的小数位数
*/
function getRoundedValue( objValue, index)
{
	return Math.round(objValue * Math.pow(10, index)) / Math.pow(10, index);
}

/**
 *转中文。
 */
function num_chinese(num)
{
	var pResult = "", j;

	j = Math.floor(num/100000000);
	pResult = ten_chinese(j, pResult, "亿");
	num = num - j * 100000000;

	j = Math.floor(num/10000000);
	pResult = ten_chinese(j, pResult, "仟");
	num = num - j * 10000000;

	j = Math.floor(num/1000000);
	pResult = ten_chinese(j, pResult, "佰");
	num = num - j * 1000000;

	j = Math.floor(num/100000)
	pResult = ten_chinese(j, pResult, "拾")
	num = num - j * 100000

	j = Math.floor(num/10000)
	pResult = ten_chinese(j, pResult, "万")
	num = num - j * 10000

	j = Math.floor(num/1000)
	pResult = ten_chinese(j, pResult, "仟")
	num = num - j * 1000

	j = Math.floor(num/100)
	pResult = ten_chinese(j, pResult, "佰")
	num = num - j * 100

	j = Math.floor(num/10)
	pResult = ten_chinese(j, pResult, "拾")
	num = num - j * 10

	j = Math.floor(num/1)
	pResult = ten_chinese(j, pResult, "元")
	num = num - j * 1
	
	num = getRoundedValue(num, 2);
	if(num != 0)
	{
		j = Math.floor( num * 10)
		pResult = ten_chinese(j, pResult, "角")

		num = num - j / 10
		j = Math.round(num * 100, 1);
		pResult = ten_chinese(j, pResult, "分")
	}

	if(pResult.substring(pResult.length - 1, pResult.length) == "零")
	{
		pResult = pResult.substring(0, pResult.length - 1);
	}	

	return pResult;
}

/**
 *转换。
 */
function ten_chinese(i, cchar, c2)
{
	var c1 = "";
	if(i != 0)
	{
		switch(i)
		{
			case 1:
				c1 = "壹";
				break;
			case 2:
				c1 = "贰"
				break;
			case 3:
				c1 = "叁";
				break;
			case 4:
				c1 = "肆"
				break;
			case 5:
				c1 = "伍"
				break;
			case 6:
				c1 = "陆"
				break;
			case 7:
				c1 = "柒"
				break;
			case 8:
				c1 = "捌"
				break;
			case 9:
				c1 = "玖"
				break;
		}
			
		c1 = cchar + c1 + c2
	}
	else
	{
		if(cchar.length != 0)
		{
			if(cchar.substring(cchar.length - 1, cchar.length) != "零")
			{
				c1 = cchar + "零"
			}
			else
			{
				c1 = cchar;
			}
			
			if(c2 == "双" || c2 == "箱")
			{
				c1 = c1.substring(0,c1.length - 1) + c2 + "零";
			}
			else if(c2 == "万")
			{
				c1 = c1.substring(0,c1.length - 1) + "万零";
			}
			else if(c2 == "亿")
			{
				c1 = c1.substring(0,c1.length - 1) + "亿零";
			}
		}
	}
	return c1;
}

function tset(){
 alert('test');
}

/**行变色*/
  function tr_old_changeTRColor(tr){
  tr.style.backgroundColor=""+old_for_row.style.backgroundColor+"";
  }

  function tr_new_changeTRColor(tr2){
  tr2.style.backgroundColor=""+new_for_row.style.backgroundColor+"";
  }

  function test(){
  alert(old_for_row.style.backgroundColor);
  }
  function getSelectedInfo(tarName){
			var tarObjs = document.getElementsByName(tarName);
			if(!tarObjs) return 0;
			var selectInfo = 0;
			for(var i=0;i<tarObjs.length;i++){
				if(tarObjs[i].selectedIndex) return tarObjs[i].selectedIndex;
				if(tarObjs[i].checked){
					selectInfo++;
				}
			}
			return selectInfo;
		}